﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Kz.Telegram.Bot.Infrastructure.Helpers
{
    /// <summary>
    /// 钉钉处理帮助类
    /// </summary>
    public class DingTalkUtils
    {
        /// <summary>
        /// 钉钉通知开关
        /// </summary>
        public static bool Switch { get; set; } = true;

        #region 钉钉推送文本消息

        /// <summary>
        /// 钉钉推送调用自定义机器人发Txt消息 
        /// </summary>
        /// <param name="webhook"></param>
        /// <param name="textMsg"></param>
        /// <param name="vsMobile"> ["156xxxx8827", "189xxxx8325"]</param>
        /// <param name="isAt">true/false</param>
        /// <returns></returns>
        public static string SendMessage(string webhook, string textMsg, string[] vsMobile = null, string isAt = "")
        {
            if (!Switch) return string.Empty;

            string msg = string.Empty;
            int num = 1;
            msg = PushMessage(webhook, textMsg, vsMobile, isAt, num);
            if (string.IsNullOrEmpty(msg))
            {
                num++;
            }
            //第一次推送失败后再推4次，超过3次的，写日志
            while (num <= 5 && string.IsNullOrEmpty(msg))
            {
                msg = PushMessage(webhook, textMsg, vsMobile, isAt, num);
                num++;
                System.Threading.Thread.Sleep(1000 * 2); // 每次执行完毕，休眠2秒
            }
            return msg;
        }

        /// <summary>
        /// 推送文本
        /// </summary>
        /// <param name="webhook"></param>
        /// <param name="textMsg"></param>
        /// <param name="vsMobile"></param>
        /// <param name="isAt"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string PushMessage(string webhook, string textMsg, string[] vsMobile, string isAt, int num)
        {
            try
            {
                object message = new
                {
                    msgtype = "text",
                    text = new
                    {
                        content = textMsg,
                    },
                    at = new
                    {
                        atMobiles = vsMobile,
                        isAtAll = isAt
                    }
                };

                System.Net.WebClient webclient = new System.Net.WebClient();
                string s = JsonConvert.SerializeObject(message);
                webclient.Headers.Add("Content-Type", "application/json; charset=utf-8");
                byte[] bytes = Encoding.UTF8.GetBytes(s);
                var arr = webclient.UploadData(webhook, "POST", bytes);
                string str = Encoding.UTF8.GetString(arr).ToString();
                if (str.IndexOf("ok") > 0)
                {
                    webclient.Dispose();
                    return JsonConvert.DeserializeObject(str).ToString();
                }
                else
                {
                    if (num >= 3)
                    {
                        //LogUtils.WriteLog("", num + "次数：" + textMsg + "\r\n" + "钉钉异常：" + str);
                    }
                    return str;
                }
            }
            catch (Exception ex)
            {
                //LogUtils.WriteLog("", textMsg + "\r\n异常：" + ex);
                return "异常：" + ex;
            }
        }

        #endregion

        #region 钉钉推送文件

        public static string SendFile(string fileUrl)
        {
            if (!Switch) return string.Empty;

            string msg = string.Empty;
            int num = 1;
            msg = PushFile(fileUrl);
            if (string.IsNullOrEmpty(msg))
            {
                num++;
            }
            //第一次推送失败后再推4次，超过3次的，写日志
            while (num <= 5 && string.IsNullOrEmpty(msg))
            {
                msg = PushFile(fileUrl);
                num++;
                System.Threading.Thread.Sleep(1000 * 2); // 每次执行完毕，休眠2秒
            }
            return msg;
        }

        /// <summary>
        /// 钉钉提醒
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static void Remind(string message)
        {
            if (!Switch) return;

            var dingTalkUrl = "https://oapi.dingtalk.com/robot/send?access_token=a71d3530fd12dc922c02ae46b761a1d6ec77337254832fe9b33da8bebee3c9fa";
            SendMessage(dingTalkUrl, message);
        }

        /// <summary>
        /// 推送文件
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <returns></returns>
        public static string PushFile(string fileUrl)
        {
            if (!Switch) return string.Empty;
            try
            {
                var url = "";//文件上传路径

                string fileName = fileUrl;//文件全路径(e:\abc.txt)
                string safeFileName = Path.GetFileName(fileName);//文件名(abc.txt)

                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                client.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data
                client.QueryString["fname"] = safeFileName;
                byte[] fileb = client.UploadFile(new Uri(url), "POST", fileName);
                string res = Encoding.UTF8.GetString(fileb);

                return res;
            }
            catch (Exception ex)
            {
                return "异常：" + ex;
            }
        }

        #endregion

    }
}
